package tools

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
)

/*--- 对称加密 公钥加密, 私钥解密; 适用场景,给二进制文件设置激活码用 ---*/
// 加密函数
func rsaEncrypt(publicKey *rsa.PublicKey, data []byte) ([]byte, error) {
	ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, data)
	if err != nil {
		return nil, err
	}
	return ciphertext, nil
}

// 解密函数
func rsaDecrypt(privateKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {
	plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
	if err != nil {
		return nil, err
	}
	return plaintext, nil
}

// pemDecodePublicKey 解码PEM格式的公钥并返回 *rsa.PublicKey
func pemDecodePublicKey(pemString string) (*rsa.PublicKey, error) {
	// 从字符串中解码PEM块
	block, _ := pem.Decode([]byte(pemString))
	if block == nil || block.Type != "PUBLIC KEY" {
		return nil, fmt.Errorf("failed to parse PEM block containing public key")
	}

	// 解析PKIX格式的公钥
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	// 断言类型为 *rsa.PublicKey
	pub, ok := pubInterface.(*rsa.PublicKey)
	if !ok {
		return nil, fmt.Errorf("public key is not of type *rsa.PublicKey")
	}

	return pub, nil
}

// pemDecodePrivateKey 解码PEM格式的私钥并返回 *rsa.PrivateKey
func pemDecodePrivateKey(pemString string) (*rsa.PrivateKey, error) {
	// 从字符串中解码PEM块
	block, _ := pem.Decode([]byte(pemString))
	if block == nil || block.Type != "RSA PRIVATE KEY" {
		return nil, fmt.Errorf("failed to parse PEM block containing private key")
	}

	// 解析PKCS#1格式的私钥
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("failed to parse private key: %v", err)
	}

	return privateKey, nil
}
func RsaEncrypt(baseContent string) (str string, err error) {
	publicKey, err := pemDecodePublicKey(publicKeyString)
	if err != nil {
		return
	}
	encryptedMessage, err := rsaEncrypt(publicKey, []byte(baseContent))
	if err != nil {
		return
	}
	str = string(encryptedMessage)
	return
}
func RsaDecrypt(baseContent string) (str string, err error) {
	privateKey, err := pemDecodePrivateKey(privateKeyString)
	if err != nil {
		return
	}
	decryptedMessage, err := rsaDecrypt(privateKey, []byte(baseContent))
	if err != nil {
		return
	}
	str = string(decryptedMessage)
	return
}

const publicKeyString = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxY8OyXtuOd/Nz/5g9g9V
ccSbeVM/hxg5+RAbjgWqawzxtV95cxaeBHDGh/KjjqRKbm8iIblkKx7EsPswRw3J
YKdSSNqj0eZzOY+5MIEd4tXES8EoMfaM/WZLnr3nW6IiffhBY7eOt2OYjbkPdbHa
u3ADUoFbPi3Qtw8OIkqsgqHhr4OLnmi7rVzEnRqP31J5lTUnKxF5bEaQ5zClyUJO
xBMejXdGSt6Em38EpbJHUVfcBnVytazRqFfbPC6YNFGBuXiY8LUS6ZzIcfeQQhUK
9GAXbDzd9ftGQO0nGdIrO+FF+m582RA7i0/IUXdV6zbrLcqSODwdec+AO6l/wQrG
rQIDAQAB
-----END PUBLIC KEY-----

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwqJ7iW5aKWI9ecZ+FHrk
u849CsLUYX3b8ySfAPEhljYQnujixzy/g7bORvMQ+RamaDBN4EO76f9jfSaQVMak
oyGRk9yCDz4a9sLcVzjt2K3ncuvqeMHnKMOmrDrML1Z5UQAlpcrqlDW45cOOQHbq
p8qyYgS6DGf0wFCxb8sLKdXi9kJvcBtyZwQb5azNYC6KLEBitYgGprnq/OGZ9vAF
w7XNnkCWyK0tevls1aSr2tdoqFmanvMtYUAst7KQo5T+4S8oVFSj6GVX2zhoJc7s
F428f2WsOIDsCWpblhsg6uaXKoN/wOyEQkv3hTf+PFv3ueGLEctPm9ejeIpK4Swl
NQIDA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dooLTWBlD6UftUPfTFAUAyxn3w2q+TM3UZo332q/xu7zHKjJINHXnvdsY7iV4
MPgaShXvV0G0hqmlRc43IyMjHDMB1bXcaVrLiEOf6OMZhqW3OQwn
-----END RSA PRIVATE KEY-----`

func getKeyPairsFromFile(publicKeyFile string, privateKeyFile string) (publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey, err error) {
	contentPub, err := ReadFileContent(publicKeyFile)
	if err != nil {
		return
	}
	publicKey, err = pemDecodePublicKey(contentPub)
	if err != nil {
		return
	}
	contentPri, err := ReadFileContent(privateKeyFile)
	if err != nil {
		return
	}
	privateKey, err = pemDecodePrivateKey(contentPri)
	if err != nil {
		return
	}
	return
}
